package common.convert;


import com.google.common.base.Preconditions;
import common.serializer.Serializer;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2020/9/22 14:04
 */
public class GenericMessageConvert implements MessageConverter {

    private Serializer serializer;

    public GenericMessageConvert(Serializer serializer){
        Preconditions.checkNotNull(serializer);
        this.serializer = serializer;
    }

    //把 springframework.amqp.messaging 的message 转成 我们自己api 中的Message
    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        return this.serializer.deSerializer(message.getBody());
    }

    //把 api中的message对象 转成springframework.amqp  的messaging。这样才能在mq上传播 也就是做序列化操作
    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        //Object 就是自己的java类
        return new Message(this.serializer.serializerToBytes(o),messageProperties);
    }
}
